import {
	userInfo
} from '@/api/user'
import {
	v4 as uuidv4
} from 'uuid';
const state = () => ({
	user: {},
	token: '',
	deviceId: 1221, // 设备Id
});
// 同步
const mutations = {
	// 用户信息
	SET_USER(state, user) {
		state.user = user;
		// console.log(333333333,user);
		if (!user.phone && !user.vipTime) {
			if (user.useViewsNum >= user.viewsNum) {
				uni.setStorageSync('infinite', false)
			}else{
					uni.setStorageSync('infinite', true)
			}

		} else {
			if (user.phone) {
				uni.setStorageSync('infinite', true)
			}
			if (user.vipTime&&(new Date(user.vipTime).getTime() >= new Date().getTime())) {
				uni.setStorageSync('infinite', true)
			}

		}
	},
	// token
	SET_TOKEN(state, token) {
		state.token = token;
	},
	// 设备ID
	SET_DEVICEID(state, deviceId) {
		state.deviceId = deviceId;
	},
}
// 异步
const actions = {
	// 获取用户信息
	async getUser({
		state,
		commit,
		dispatch
	}) {
		// let user =uni.getStorageSync('userInfo')
		// if (user) {
		// 	commit('SET_USER', JSON.parse(user));
		// 	console.log('旧userInfo',  JSON.parse(user));
		// } else {
		const {
			data
		} = await userInfo({
			deviceId: uni.getStorageSync('deviceId')
		});
		uni.setStorageSync('userInfo', JSON.stringify(data))
		uni.setStorageSync('token', data.token)
		commit('SET_USER', data);
		// }
	},
	// 获取设备Id
	async getDeviceId({
		commit,
		dispatch
	}) {
		let deviceId = uni.getStorageSync('deviceId')
		if (deviceId) {
			await dispatch('getUser')
		} else {
			let id = uni.getSystemInfoSync().deviceId
			// let id = uuidv4()
			uni.setStorageSync('deviceId', id)
			commit('SET_DEVICEID', id);
			await dispatch('getUser')
		}
	}
}
export default {
	state,
	mutations,
	actions
};